package com.example.lenovo.tianqi.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.lenovo.tianqi.R;
import com.example.lenovo.tianqi.adapter.MyFragmentPagerAdapter;
import com.example.lenovo.tianqi.dialog.OtherCityDialog;
import com.example.lenovo.tianqi.fragment.MainFragment;
import com.example.lenovo.tianqi.fragment.ManagerFragment;
import com.example.lenovo.tianqi.util.MySharedpreference;
import com.example.lenovo.tianqi.util.NetState;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,FloatingActionButton.OnClickListener,ImageView.OnLongClickListener{
    //顶部导航栏
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private Toolbar toolbar;
    private ImageView banner;
    //侧滑菜单栏
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private View headerview;

    private CollapsingToolbarLayout toolbarLayout;
    private FloatingActionButton floatingActionButton;
    private long exittime=0;
    private FragmentPagerAdapter fragmentPagerAdapter;
    private ArrayList<Fragment> fragments;
    private MainFragment mainFragment;
    private ManagerFragment managerFragment;
    private int REQUEST_ALBUM_OK=250;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editor=MySharedpreference.getInstance(MainActivity.this);
        initView();
        initDrawer();
    }

    private void initView() {
        banner=findViewById(R.id.banner);
        mainFragment=new MainFragment(new MainFragment.InitInfoListener() {
            @Override
            public void InitSuccessed(String cityName) {
                toolbarLayout.setTitle(cityName);
            }
        });

        managerFragment=new ManagerFragment();
        fragments=new ArrayList<>();
        fragments.add(mainFragment);
        fragments.add(managerFragment);
        fragmentPagerAdapter=new MyFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        viewPager=(ViewPager)findViewById(R.id.viewPager);
        tabLayout=(TabLayout)findViewById(R.id.tabLayout);
        banner=(ImageView)findViewById(R.id.banner);
        toolbar=(Toolbar)findViewById(R.id.toolbar);
        toolbarLayout=(CollapsingToolbarLayout)findViewById(R.id.toolbar_layout);
        navigationView=(NavigationView)findViewById(R.id.navigation_view);
        drawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout) ;
        floatingActionButton=findViewById(R.id.FaButton);
        tabLayout.setupWithViewPager(viewPager,false);
        toolbarLayout.setTitle(MySharedpreference.preferences.getString("City","成都"));
        setSupportActionBar(toolbar);
        viewPager.setAdapter(fragmentPagerAdapter);
        headerview=navigationView.getHeaderView(0);
        floatingActionButton.hide();
        floatingActionButton.setOnClickListener(this);
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position) {
                if (position==0) {
                   floatingActionButton.hide();
                } else {
                   floatingActionButton.show();
                }
            }
        });
        banner.setOnLongClickListener(this);
    }

    private void initDrawer() {
        if (navigationView != null) {
            //生成toolbar上的菜单项按钮
            ActionBarDrawerToggle toggle =
                    new ActionBarDrawerToggle(this, drawerLayout, toolbar,R.string.open_nav,
                            R.string.close_nav);
            drawerLayout.addDrawerListener(toggle);
            toggle.syncState();
        }
    }

    @Override
    //drawerLayout.isDrawerOpen判断是否打开了侧滑栏
    //onBackPressed（）监听手机back键
    //System.currentTimeMillis()获取从1970年1月1日起的毫秒数
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(navigationView))
        {
            drawerLayout.closeDrawer(navigationView);
        }
        else{
            if((System.currentTimeMillis()-(exittime))>2000)
            {
                Toast.makeText(this, "再次点击返回键退出应用", Toast.LENGTH_SHORT).show();
                exittime=System.currentTimeMillis();
            }
            else if ((System.currentTimeMillis()-(exittime))<=2000)
            {
                finish();
            }
           else{ super.onBackPressed();}
        }
    }

    @Override
    //    浮动按钮点击事件
    public void onClick(View v) {
        //首先跳转到列表页面，通过startActivityForResult实现页面跳转传值
        Intent intent = new Intent(MainActivity.this,CitySelectorAvtivity.class);
        startActivityForResult(intent,CitySelectorAvtivity.SelectorSuccessFromMultiCity);

    }

    @Override
//    侧滑栏item点击事件
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.navigation_city:
                Intent intent=new Intent(MainActivity.this,CitySelectorAvtivity.class);
                startActivityForResult(intent,CitySelectorAvtivity.SelectorSuccessFromMenu);
                break;
            case R.id.navigation_other_city:
                drawerLayout.closeDrawer(navigationView);
                new OtherCityDialog(MainActivity.this, new OtherCityDialog.MyDialogListenner() {
                    @Override
                    public void Clicksure(String cityName) {
                        UpdataViewForMain(cityName);
                    }
                }).show();
                break;
            case R.id.navigation_multi_cities:
                drawerLayout.closeDrawer(navigationView);
                viewPager.setCurrentItem(1);
                break;
            case R.id.navigation_set:
                startActivity(new Intent(MainActivity.this,SettingActivity.class));
                break;
            case R.id.navigation_about:
                startActivity(new Intent(MainActivity.this, AboutActivity.class));
                break;
        }
        return true;
    }

    private void UpdataViewForMain(String cityName) {
        drawerLayout.closeDrawer(navigationView);
        String OldCity=MySharedpreference.preferences.getString("City",null);
        editor.putString("City",cityName);
        editor.commit();
        //更新数据
        mainFragment.UpDataUi(OldCity);
        mainFragment.mainRecyclerview.smoothScrollToPosition(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CitySelectorAvtivity.SelectorSuccessFromMenu) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    return;
                }
                Bundle bundle = data.getExtras();
                //城市名称
                String cityName=bundle.getString("CityName");
                //获取到城市名后自行使用

                UpdataViewForMain(cityName);
            }
        }
        else if (requestCode==CitySelectorAvtivity.SelectorSuccessFromMultiCity)
        {
            //来自于多城市添加的回调
            if (resultCode==RESULT_OK){
                if(data==null)
                {
                    return;
                }
                Bundle bundle = data.getExtras();
                //城市名
                String cityName=bundle.getString("CityName");
                Log.d("mmp",cityName);
                UpdataViewForMultiCity(cityName);
            }
        }
        else if(requestCode == REQUEST_ALBUM_OK) {
            //Log.d("cc", "onActivityResult:相册 " + data.getData().toString());
            ContentResolver resolver = getContentResolver();

            try {
                InputStream inputStream = resolver.openInputStream(data.getData());

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                banner.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        }

    private void UpdataViewForMultiCity(String cityName) {
        int MultiCityNum = MySharedpreference.preferences.getInt("MultiCityNum",0);
        //获取主页城市
        String mainCity = MySharedpreference.preferences.getString("City","成都");
        if(MultiCityNum>=3)
        {
            Toast.makeText(MainActivity.this,"多城市数量不能超过3个",Toast.LENGTH_SHORT).show();
        }
        else if(mainCity.contains(cityName)||cityName.contains(mainCity))
        {
            Toast.makeText(MainActivity.this,"该城市已经存在",Toast.LENGTH_SHORT).show();
        }
        else if(MultiCityNum!=0)
        {
            int i;
            for(i=1;i<=MultiCityNum;i++)
            {
                if(cityName.equals(MySharedpreference.preferences.getString("MultiCity"+i,null)))
                {
                    Toast.makeText(MainActivity.this,"该城市已经存在",Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            if(i>MultiCityNum)//没有查找到重名城市
            {
                if(NetState.isNetworkAvailable(getApplicationContext()))
                {
                    MultiCityNum++;
                    editor.putString("MultiCity"+MultiCityNum,cityName);
                    editor.putInt("MultiCityNum",MultiCityNum);
                    editor.commit();
                    managerFragment.UpDataUi();
                }
                else Toast.makeText(MainActivity.this,"请检查网络",Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
            if(NetState.isNetworkAvailable(getApplicationContext()))
            {
                MultiCityNum++;
                editor.putString("MultiCity"+MultiCityNum,cityName);
                editor.putInt("MultiCityNum",MultiCityNum);
                editor.commit();
                managerFragment.UpDataUi();
            }
            else Toast.makeText(MainActivity.this,"请检查网络",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onLongClick(View v) {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent,REQUEST_ALBUM_OK);
        return true;
    }
}

